<template>
  <div class="sui-pagination clearfix">
    总共{{ totalPage }}页
    <ul>
      <li :class="{ disabled: pageNo == 1 }" @click="$emit('chooseLi', pageNo - 1)">
        <a>上一页</a>
      </li>
      <!-- 第一页 -->
      <li>
        <a v-if="pageStartAndEnd.start > 1" @click="$emit('chooseLi', 1)">{{ 1 }}</a>
      </li>
      <!-- 省略号 -->
      <li>
        <a v-if="pageStartAndEnd.start > 2">...</a>
      </li>
      <template v-for="index in pageStartAndEnd.end">
        <li :key="index" @click="$emit('chooseLi', index)" v-if="index >= pageStartAndEnd.start">
          <a :class="{ active: index == pageNo }">{{ index }}</a>
        </li>
      </template>
      <!-- 省略号 -->
      <li>
        <a v-if="pageStartAndEnd.end + 1 < totalPage">...</a>
      </li>
      <!-- 最后一页 -->
      <li>
        <a v-if="pageStartAndEnd.end < totalPage" @click="$emit('chooseLi', totalPage)">{{ totalPage }}</a>
      </li>
      <li :class="{ disabled: pageNo == totalPage }" @click="$emit('chooseLi', pageNo + 1)">
        <a>下一页</a>
      </li>
    </ul>
    <div>
      <span>共{{ total }}条</span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'detail',
  props: ['total', 'pageSize', 'pageNo'],
  computed: {
    // 总共页数
    totalPage() {
      return Math.ceil(this.total / this.pageSize)
    },
    pageStartAndEnd() {
      let start = 0
      let end = 0
      // 当总页数小于5时
      if (this.totalPage < 5) {
        start = 1
        end = this.totalPage
      } else {
        // 页面总数大于5时
        start = this.pageNo - 2
        end = this.pageNo + 2
        // 当开始页小于1时
        if (start <= 1) {
          start = 1
          end = 5
        }
        // 当结束页大于总页数时
        if (end > this.totalPage) {
          start = this.totalPage - 4
          end = this.totalPage
        }
      }
      return { start, end }
    },
  },
}
</script>

<style lang="scss" scoped>
.sui-pagination {
  margin: 18px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  ul {
    margin-left: 0;
    margin-bottom: 0;
    vertical-align: middle;
    .disabled {
      pointer-events: none;
    }
    li {
      line-height: 18px;
      display: inline-block;
      margin: 0 2px;
      a {
        position: relative;
        float: left;
        line-height: 18px;
        text-decoration: none;
        background-color: #fff;
        border: 1px solid #e0e9ee;
        margin-left: -1px;
        font-size: 14px;
        padding: 4px 10px;
        color: #333;
      }
      .active {
        background-color: #409eff;
        color: #fff;
        cursor: default;
      }
    }
  }
  div {
    color: #333;
    font-size: 14px;
    margin-left: 30px;
  }
}
</style>
